问题描述(难度简单-112/113/437)
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
1 | 5 |
Return:
1 | [ |
P112
Using Recursive
1 | package P112; |
P113
Using Recursive
1 | package P113; |
Using Recursive+LinkedList
每次递归出来数组无法指定插入位置(数组不利于插入),换成链表,避免了重新换位置。
1 | package P113; |
P437
类比上面两题虽然这道标记为简单,但是感觉理解和逻辑上难度更大。
Using Recursive
对于递归问题我们首先要明确我们需要解决的问题,这里需要解决的问题是,二叉树中有几个和为指定sum的组合。我们的输入是root和sum,输出是组合数量。然后我们尝试将这个问题分解为子问题,要找到任意节点为根,和为sum的所有可能。所以第一个递归是遍历以每个节点为根的和为sum的数量,第二个递归是根为特定节点的和为sum的数量。
- 明确需要解决的问题。函数的输入输出可递归分解为子问题。
- 构造出递归的基本结构。
1 | package P437; |
总结
在写递归的过程中首先参考递归的书写范式,逆向考虑递归要跟踪调用栈实际上非常复杂。